<?php
namespace App\Controller\App;

use App\Query\ConfigQuery;
use App\Query\UserLogQuery;

class UserWalletController extends Controller
{
    // 判断今日是否红分
    protected function day($user)
    {
        $count = UserLogQuery::day(
            UserLogQuery::type('money_wallet_red', UserLogQuery::user($user))
        )->count();
        
        if($count)
        {
            $this->error('money_wallet_red_day');
        }
    }
    
    // 转入钱包
    public function index()
    {
        $user = $this->auth();
        
        // 金额
        $money = (int) $this->input('money');
        
        // 判断是否整千
        if($money % 1000)
        {
            $this->error('thousand');
        }
        
        // 扣余额
        if(!$user->moneyMake($money, '转入钱包'))
        {
            $this->error('money');
        }
        
        // 加钱包
        $user->moneyWalletAdd($money, '转入钱包');
        
        $this->message('ok');
    }
    
    // 转出钱包
    public function out()
    {
        $user = $this->auth();
        
        // 金额
        $money = (int) $this->input('money');
        
        // 判断是否整千
        if($money % 1000)
        {
            $this->error('thousand');
        }
        
        // 判断是否分红过
        $this->day($user);
        
        // 扣钱包
        if(!$user->moneyWalletMake($money, '转出钱包'))
        {
            $this->error('money_wallet');
        }
        
        // 加余额
        $user->moneyAdd($money, '转出钱包');
        
        $this->message('ok');
    }
    
    // 签到
    public function red()
    {
        $user = $this->auth();
        
        // 判断今日是否红分
        $this->day($user);
        
        // 算出今日转入金额
        $day = (float) UserLogQuery::day(
            UserLogQuery::moneyType('money_wallet', UserLogQuery::user($user))
        )->sum('money');
        
        // 如果今日为负数
        $day = $day > 0 ? $day : 0;
        
        // 算出比例
        $money = ConfigQuery::bi(ConfigQuery::get(), 'money_wallet_red', $user->money_wallet - $day);

        // 加入分红
        if($money > 0)
        {
            $user->moneyWalletRedAdd($money, '每日签到钱包分红', 'money_wallet_red');
            
            $this->message('ok');
        }

        $this->error('money_wallet');
    }
    
    // 分红转出
    public function redOut()
    {
        $user = $this->auth();
        
        // 金额
        $money = (int) $this->input('money');
        
        // 判断是否整千
        if($money % 100)
        {
            $this->error('hundred');
        }
        
        // 扣钱包分红
        if(!$user->moneyWalletRedMake($money, '转出钱包分红'))
        {
            $this->error('money_wallet_red');
        }

        // 加补贴
        $user->moneyFullAdd($money, '转出钱包分红', 'money_wallet_full');
        
        $this->message('ok');
    }
}
